package com.base.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.admin.context.GlobalContext;
import com.base.admin.entity.AdminUser;
import com.base.admin.exception.BizException;
import com.base.admin.mapper.AdminUserMapper;
import com.base.admin.service.AdminUserService;
import com.base.admin.util.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* @author 11243
* @description 针对表【app_admin_user】的数据库操作Service实现
* @createDate 2024-02-22 20:26:39
*/
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser>
    implements AdminUserService {


    @Value("${token.expire}")
    private String tokenExpire;

    @Value("${token.key}")
    private String tokenKey;

    @Override
    public String login(String username, String password) {
        LambdaQueryWrapper<AdminUser> adminUserWrapper = new LambdaQueryWrapper<>();
        adminUserWrapper.eq(AdminUser::getUsername, username);
        AdminUser result = getOne(adminUserWrapper);
        if (Objects.isNull(result)) {
            throw new BizException("用户名不存在");
        }

        if (!result.getPassword().equals(DigestUtils.sha256Encrypt(password))) {
            throw new BizException("密码错误");
        }
        Map<String, Object> tokenParam = new HashMap<>(16);
        // 设置过期时间
        tokenParam.put(JWTPayload.EXPIRES_AT, DateUtil.offsetDay(new Date(), Integer.parseInt(tokenExpire)).getTime());
        tokenParam.put("uname", result.getUsername());
        // 生成token
        return JWTUtil.createToken(tokenParam, tokenKey.getBytes());
    }

    @Override
    public AdminUser getLoginUserInfo() {
        AdminUser loginUser = GlobalContext.getLoginUser();
        loginUser.setPassword("");
        return loginUser;
    }
}




